package com.multi.tool.concurrent.vol;


/**
 * @author zhengpeng.wang
 */
public class VolatileDemo1 {

    private /*volatile*/ int count = 0;

    public void addCount() {
        count++;
    }

    //多次运行结果最后的count都不是预计的10，这说明使用volatile变量并不能保证线程安全
    public static void main(String[] args) {
        VolatileDemo1 volatileTest = new VolatileDemo1();
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                try {
                    Thread.sleep(100);
                    //使用 同步代码快 保证线程安全
/*                    synchronized (volatileTest){
                        volatileTest.addCount();
                    }*/
                    volatileTest.addCount();

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
        }

        try {
            Thread.sleep(1000);
            System.out.println(volatileTest.count);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
